/************************************************************
 *  * GOSwift CONFIDENTIAL
 * __________________
 * Copyright (C) 2013-2014 CWSwift Technologies. All rights reserved.
 *
 * NOTICE: All information contained herein is, and remains
 * the property of CWSwift Technologies.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from GOSwift Technologies.
 * knight lu 349919133
 */

#import "UIViewController+ServiceNetwork.h"
#import <CommonCrypto/CommonDigest.h>

#define ServiceNetwork_Host     @"http://cwapp.oschina.mopaas.com/index.php"
#define ServiceNetwork_AppId    @"66"
#define ServiceNetwork_AppKey   @"7072bd4510e6d892bc40fd5cc308a577"
#define APP_ISVIPJXT @"1"   //新加请求参数,用于识别vip用户

#define ServiceNetwork_Timeout  15

static inline char hexChar(unsigned char c) {
    return c < 10 ? '0' + c : 'a' + c - 10;
}

static inline void hexString(unsigned char *from, char *to, NSUInteger length) {
    for (NSUInteger i = 0; i < length; ++i) {
        unsigned char c = from[i];
        unsigned char cHigh = c >> 4;
        unsigned char cLow = c & 0xf;
        to[2 * i] = hexChar(cHigh);
        to[2 * i + 1] = hexChar(cLow);
    }
    to[2 * length] = '\0';
}

NSString * _md5(const char *string) {
    static const NSUInteger LENGTH = 16;
    unsigned char result[LENGTH];
    CC_MD5(string, (CC_LONG)strlen(string), result);
    
    char hexResult[2 * LENGTH + 1];
    hexString(result, hexResult, LENGTH);
    
    return [NSString stringWithUTF8String:hexResult];
}

@implementation UIViewController (ServiceNetwork)


//得到加密字串
/*
 * args   参数字串
 */
+ (NSString *)getSign:(NSString *)args
{
    NSString *sign = args;//[args stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    //3次MD5
    sign = [UIViewController strMD5:sign];
    sign = [UIViewController strMD5:sign];
    sign = [UIViewController strMD5:sign];
    
    sign = [NSString stringWithFormat:@"6b5d88dad8602d689db1885ae985d62f%@", sign];
    
    //2次MD5
    sign = [UIViewController strMD5:sign];
    sign = [UIViewController strMD5:sign];
    
    return sign;
}

+ (NSString *)strMD5:(NSString *)str
{
    return _md5([str UTF8String]);
}




- (void)GET:(NSString *)fun successBlock:(NetworkSuccessBlock)success failureBlock:(NetworkFailureBlock)failure
{
    [self GET:fun args:nil successBlock:success failureBlock:failure];
}

- (void)GET:(NSString *)fun args:(NSDictionary *)argsDic
                    successBlock:(NetworkSuccessBlock)success
                    failureBlock:(NetworkFailureBlock)failure
{
    if (!fun.length)
    {
        NSLog(@"fun参数不能为空!!!");
    }
 
    NSString *requestStr;//网址
    NSString *argsStr;//参数
    
    
//    未加密前的接口
    requestStr = [NSString stringWithFormat:@"appkey=%@&appid=%@&isgetjxt=%@&fun=%@",ServiceNetwork_AppKey,ServiceNetwork_AppId,APP_ISVIPJXT, fun];
    argsStr = [UIViewController argsStrForDic:argsDic andEncrypt:NO];
    
//    拼接
    if (argsStr.length)
    {
        requestStr = [NSString stringWithFormat:@"%@&%@", requestStr, argsStr];
    }
    NSLog(@"未加密前的接口：%@?%@",ServiceNetwork_Host,requestStr);
    
//    加密
     NSString *sign = [UIViewController getSign:requestStr];
    
    //DES加密
    NSString *encryptAppKey = [NSString encodeToPercentEscapeString:[NSString encryptUseDES:ServiceNetwork_AppKey]];
    
    NSString *encryptAppId = [NSString encodeToPercentEscapeString:[NSString encryptUseDES:ServiceNetwork_AppId]];
    
    NSString *encryptIsVIPJXT = @"5sP/8vtSS8M=";
    
    
    NSString *encryptAction = [NSString encodeToPercentEscapeString:[NSString encryptUseDES:fun]];
    
    requestStr = [NSString stringWithFormat:@"appkey=%@&appid=%@&isgetjxt=%@&fun=%@",encryptAppKey,encryptAppId,encryptIsVIPJXT,encryptAction];
    
    argsStr = [UIViewController argsStrForDic:argsDic andEncrypt:YES];
    if (argsStr.length){
        requestStr = [NSString stringWithFormat:@"%@&%@",requestStr,argsStr];
    }
    
    if ([argsDic objectForKey:@"http"]) {
        requestStr = [NSString stringWithFormat:@"%@?%@&sign=%@", [argsDic objectForKey:@"http"], requestStr, sign];
        NSLog(@"新网址:%@",requestStr);
    }else{
        requestStr = [NSString stringWithFormat:@"%@?%@&sign=%@", ServiceNetwork_Host, requestStr, sign];
        NSLog(@"默认网址：%@",requestStr);
    }
    
    //判断是不是文件
    if ([argsDic objectForKey:@"file"]) {
        NSLog(@"上传图片:%@",requestStr);
        
        [self fileUpload:requestStr dic:argsDic];
        return ;
    }
    
    
    [self httpGetRequest:requestStr andBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         
         NSError *parseError = nil;
         
         //去掉多余的空格
         NSString *operationStr = [operation.responseString stringByReplacingOccurrencesOfString:@"\t" withString:@""];
         
         NSDictionary *xmlDic = [XMLReader dictionaryForXMLString:operationStr error:&parseError];
         
         if (xmlDic.count)
         {
             success(xmlDic);
         }
         else
         {
             failure();
         }
     }
    failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         failure();
        
     }];
}

- (void)fileUpload:(NSString *)requestStr dic:(NSDictionary *)dicpara 
{
 
    AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:requestStr]];

    manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
    
    manager.requestSerializer.timeoutInterval = ServiceNetwork_Timeout;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/xml"];
    [manager POST:requestStr parameters:dicpara constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

    //服务器根据名字取
        NSString * headstr = [NSString stringWithFormat:@"%@/%@",[Tools getImageFilePath:[Tools getValueForKey:HEADIMAG]],HEADIMAG];
        
        if ([Tools checkFileExist:[Tools getValueForKey:HEADIMAG]] && [[Tools getValueForKey:@"type"] isEqualToString:@"selfinfo"]) {
            [formData appendPartWithFileURL:[NSURL fileURLWithPath:headstr] name:@"img_url_1" error:nil];
                //[formData appendPartWithFileData:UIImagePNGRepresentation([UIImage imageNamed:headstr]) name:@"Img1" fileName:@"1.png" mimeType:@"image/png"];
            
        }

        if ([[Tools getValueForKey:@"type"] isEqualToString:@"dyn"]) {//动态列表图
            NSString * imgStr1 = [NSString stringWithFormat:@"%@/%@",[Tools getImageFilePath:[Tools getValueForKey:DYMIMAGE_1]],DYMIMAGE_1];
            if ([Tools checkFileExist:[Tools getValueForKey:imgStr1]]) {
                [formData appendPartWithFileURL:[NSURL fileURLWithPath:imgStr1] name:@"img_url_1" error:nil];
                NSLog(@"%@",imgStr1);
            }
            
            NSString * imgStr2 = [NSString stringWithFormat:@"%@/%@",[Tools getImageFilePath:[Tools getValueForKey:DYMIMAGE_2]],DYMIMAGE_2];
            if ([Tools checkFileExist:[Tools getValueForKey:imgStr2]]) {
                [formData appendPartWithFileURL:[NSURL fileURLWithPath:imgStr2] name:@"img_url_2" error:nil];
                NSLog(@"%@",imgStr2);
            }
            
            NSString * imgStr3 = [NSString stringWithFormat:@"%@/%@",[Tools getImageFilePath:[Tools getValueForKey:DYMIMAGE_3]],DYMIMAGE_3];
            if ([Tools checkFileExist:[Tools getValueForKey:imgStr3]]) {
                [formData appendPartWithFileURL:[NSURL fileURLWithPath:imgStr3] name:@"img_url_3" error:nil];

            }
            
            NSString * imgStr4 = [NSString stringWithFormat:@"%@/%@",[Tools getImageFilePath:[Tools getValueForKey:DYMIMAGE_4]],DYMIMAGE_4];
            if ([Tools checkFileExist:[Tools getValueForKey:imgStr4]]) {
                [formData appendPartWithFileURL:[NSURL fileURLWithPath:imgStr4] name:@"img_url_4" error:nil];
                
            }
            
            NSString * imgStr5 = [NSString stringWithFormat:@"%@/%@",[Tools getImageFilePath:[Tools getValueForKey:DYMIMAGE_5]],DYMIMAGE_5];
            if ([Tools checkFileExist:[Tools getValueForKey:imgStr5]]) {
                [formData appendPartWithFileURL:[NSURL fileURLWithPath:imgStr5] name:@"img_url_5" error:nil];
                
            }
            
            NSString * imgStr6 = [NSString stringWithFormat:@"%@/%@",[Tools getImageFilePath:[Tools getValueForKey:DYMIMAGE_6]],DYMIMAGE_6];
            if ([Tools checkFileExist:[Tools getValueForKey:imgStr6]]) {
                [formData appendPartWithFileURL:[NSURL fileURLWithPath:imgStr6] name:@"img_url_6" error:nil];
                
            }
            
        }
        if ([[Tools getValueForKey:@"type"] isEqualToString:@"activityPic"]) {//活动列表列表图
            
            NSString * imgStr1 = [NSString stringWithFormat:@"%@/%@",[Tools getImageFilePath:[Tools getValueForKey:ACTIMAGE_1]],ACTIMAGE_1];
            if ([Tools checkFileExist:[Tools getValueForKey:imgStr1]]) {
                [formData appendPartWithFileURL:[NSURL fileURLWithPath:imgStr1] name:@"img_url_1" error:nil];
            }
            
            NSString * imgStr2 = [NSString stringWithFormat:@"%@/%@",[Tools getImageFilePath:[Tools getValueForKey:ACTIMAGE_2]],ACTIMAGE_2];
            if ([Tools checkFileExist:[Tools getValueForKey:imgStr2]]) {
                [formData appendPartWithFileURL:[NSURL fileURLWithPath:imgStr2] name:@"img_url_2" error:nil];
            }
            
            NSString * imgStr3 = [NSString stringWithFormat:@"%@/%@",[Tools getImageFilePath:[Tools getValueForKey:ACTIMAGE_3]],ACTIMAGE_3];
            if ([Tools checkFileExist:[Tools getValueForKey:imgStr3]]) {
                [formData appendPartWithFileURL:[NSURL fileURLWithPath:imgStr3] name:@"img_url_3" error:nil];
            }
            
        }

        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSLog(@"提交返回信息 ,%@",operation.responseString);
        
        //删除图片
        for (int i = 0 ; i < 6; i++) {
            
            NSString *str = [NSString stringWithFormat:@"dymimage_%i.png",i ];
            
            [Tools removeFile:str];
            
            NSString *str2 = [NSString stringWithFormat:@"actvImag_%i.jpg",i ];
            
            [Tools removeFile:str2];
            
        }
        [Tools removeFile:HEADIMAG];
        [Tools setValue:@"" forKey:@"type"];
        //[[SDImageCache sharedImageCache] removeImageForKey:@"" fromDisk:YES];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"提交失败Error: %@", error);
        
    }];

}

- (void)httpGetRequest:(NSString *)requestStr
   andBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
               failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:requestStr]];
    [request setHTTPMethod:@"GET"];
    [request setTimeoutInterval:ServiceNetwork_Timeout];
    
    AFHTTPRequestOperation *httpOperation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [httpOperation setCompletionBlockWithSuccess:success
                                         failure:failure];
    [httpOperation start];
}

//字典转换为参数链接
+ (NSString *)argsStrForDic:(NSDictionary *)argsDic andEncrypt:(BOOL)isEncrypt
{
    NSString *argsString = @"";
    
    NSDictionary *args = argsDic;
    
    if (args != nil)
    {
        NSArray *allKeys = [args allKeys];
        NSArray *allValues = [args allValues];
        
        for (int i=0; i<[allKeys count]; i++) {
            
            NSString *str;
            
            NSString *key = [allKeys objectAtIndex:i];
            
            NSString *value = [allValues objectAtIndex:i];
            
            if (value.length)
            {
                if (isEncrypt){
                    value = [NSString encryptUseDES:value];
                }
                value = [self encodeToPercentEscapeString:value];
                
                str = [NSString stringWithFormat:@"%@=%@&",key,value];
                
                argsString = [argsString stringByAppendingString:str];
            }
        }
        
        if([argsString hasSuffix:@"&"])
        {
            argsString = [argsString substringToIndex:[argsString length] - 1];
        }
    }
    
    return argsString;
}

//url编码
+ (NSString *)encodeToPercentEscapeString:(NSString *)input
{
    // Encode all the reserved characters, per RFC 3986
    
    // (<http://www.ietf.org/rfc/rfc3986.txt>)
    
    NSString *outputStr = (NSString *)
    
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              
                                                              (CFStringRef)input,
                                                              
                                                              NULL,
                                                              
                                                              (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                              
                                                              kCFStringEncodingUTF8));
    
    return outputStr;
}

@end
